<template>
  <view v-if="post&&post.status===1" class="post-detail">
    <mescroll-body ref="mescrollRef" :up="upOption" @init="mescrollInit" @down="downCallback" @up="upCallback">
      <view v-if="post" id="comment-up-area">
        <StarPostItem :post="post" :option="postOption" :my_user="vuex_user" @selectPost="selectPost"
          @longpressPost="longpressPost" @clickUserAvatar="clickPostUserAvatar"
          @clickUserNickname="clickPostUserNickname" @clickFocusUser="clickPostFocusUser"
          @clickChatUser="clickPostChatUser" @clickMore="clickMore" @clickSharePost="clickSharePost"
          @clickCommentPost="clickCommentPost" @toggleLike="toggleLikePost" @clickDeletePost="clickDeletePost">
        </StarPostItem>
      </view>
      <view class="comment-top">
        <view class="title">
          全部评论
        </view>
        <view class="tab">
          <view class="tab-item" :class="{ active: selectedTab === 'recommend' }" @click="selectTab('recommend')">
            推荐
          </view>
          <view class="tab-item" :class="{ active: selectedTab === 'latest' }" @click="selectTab('latest')">
            最新
          </view>
        </view>
      </view>
      <StarCommentList :list="commentList" :post_id="post.id" :option="commentOption" :my_user="vuex_user"
        @selectComment="selectComment" @clickUserAvatar="clickCommentUserAvatar"
        @clickUserNickname="clickCommentUserNickname" @clickReplyUserNickname="clickCommentReplyUserNickname"
        @longpressComment="longpressComment" @toggleLike="toggleLikeComment" @clickDeleteComment="clickDeleteComment">
      </StarCommentList>
    </mescroll-body>
    <StarCommentReply ref="starCommentReplyRef" :option="replyOption" @sendComment="sendComment"></StarCommentReply>
  </view>
</template>

<script>
  import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js';
  import StarPostItem from '@/uni_modules/star-community/components/star-post-item/star-post-item.vue'
  import StarCommentList from '@/uni_modules/star-community/components/star-comment-list/star-comment-list.vue'
  import StarCommentReply from '@/uni_modules/star-community/components/star-comment-reply/star-comment-reply.vue'

  // import mockPost from '../../mock/mockjs/post.js'
  // import mockComment from '../../mock/mockjs/comment.js'

  import {
    v4 as uuidv4
  } from 'uuid'

  export default {
    mixins: [MescrollMixin], // 使用mixin
    components: {
      StarPostItem,
      StarCommentList,
      StarCommentReply
    },
    data() {
      return {
        selectedTab: 'recommend', // 默认选择推荐标签
        postOption: {
          // showShare: false,
          // showView: false,
          // showComment: false,
          // showLike: false,
          // iconShare: '/static/share.svg',
          // iconView: '/static/view.svg',
          // iconComment: '/static/comment.svg',
          // iconLike: '/static/like.svg',
          // iconLiked: '/static/liked.svg',
        },
        commentOption: {
          // iconLike: '/static/like.svg',
          // iconLiked: '/static/liked.svg',
        },
        replyOption: {
          imgMaxCount: 9, // 选择图片最大数量
          // imgMaxSize: 5, // 单位：M
          // iconImgRemove: '/static/remove.svg'
          // iconImg: '/static/chooseImg.svg', // 选择图片icon
        },
        upOption: {
          isBounce: false,
          noMoreSize: 4, // 如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
          toTop: {
            bottom: '320rpx',
            safearea: true,
          }
        },
        post: null,
        commentList: []
      };
    },
    onShareAppMessage() {
      uniCloud.callFunction({
        name: 'star-community-count',
        data: {
          flag: 1,
          data: {
            flag: 1,
            data: {
              id: this.post.id,
              shareIncCount: 1,
            }
          }
        }
      })
      this.post.shareCount++
      if (this.post.imgList.length > 0) {
        return {
          title: this.post.title || this.post.content,
          imageUrl: this.post.imgList[0],
          query: 'id=' + this.post.id
        };
      } else {
        return {
          title: this.post.title || this.post.content,
          query: 'id=' + this.post.id
        };
      }
    },
    async onLoad(option) {
      console.log(option?.id);

      if (!option?.id) {
        uni.showToast({
          title: '帖子不存在',
          icon: 'none'
        })
        uni.navigateBack()
        return
      }

      // 拉取帖子数据
      // this.post = mockPost.generateRandomPosts(1)[0]
      this.post = await this.getPost(option.id)

      if (!this.post || this.post?.status !== 1) {
        uni.showToast({
          title: '无法查看帖子',
          icon: 'none'
        })
        uni.navigateBack()
        return
      }

      if (this.post?.status === 1 && this.post.user_id !== this.vuex_user.id) {
        uniCloud.callFunction({
          name: 'star-community-count',
          data: {
            flag: 1,
            data: {
              id: option.id,
              viewIncCount: Math.floor(Math.random() * 10) + 1, // 1-10的随机整数
            }
          }
        })
      }

      // 是否自动滑动至评论区，option?.comment === 'yes'
      if (option?.comment === 'yes') {
        // 等待dom渲染完毕，才能获取节点信息
        setTimeout(() => {
          this.goArea('#comment-up-area') // 自动滑动至评论区
          this.$refs.starCommentReplyRef.focus = true // 评论框自动聚焦
        }, 300)
      }
    },
    methods: {
      // 下拉刷新的回调
      downCallback() {
        // 这里加载你想下拉刷新的数据, 比如刷新轮播数据
        // loadSwiper();
        // 下拉刷新的回调,默认重置上拉加载列表为第一页 (自动执行 page.num=1, 再触发upCallback方法 )
        this.mescroll.resetUpScroll()
      },
      // 上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
      async upCallback(page) {
        try {
          if (!this.post || this.post?.status !== 1) {
            return
          }
          // 请求数据列表
          let list = await this.getCommentList(page)
          // 设置列表数据
          if (page.num === 1) this.commentList = [] // 如果是第一页需手动制空列表
          this.commentList = [...this.commentList, ...list] // 追加新数据
          // 联网成功的回调,隐藏下拉刷新和上拉加载的状态
          this.mescroll.endSuccess(list.length)
        } catch (err) {
          console.log(err)
        }
      },
      async getPost(id) {
        let vuex_user = this.vuex_user
        let res = await uniCloud.callFunction({
          name: 'star-community-post',
          data: {
            flag: 0,
            data: {
              my_user_id: vuex_user.id,
              id
            }
          }
        })
        return res.result.data.length > 0 ? res.result.data[0] : null
      },
      // 获取评论列表
      async getCommentList(page) {
        // let fatherCommentList = mockComment.generateRandomComments(page.size)
        // let randomInteger = Math.floor(Math.random() * 11) // 随机生成0-10个子评论
        // let childCommentList = mockComment.generateRandomComments(randomInteger)
        // return fatherCommentList.map(comment => ({
        // 	...comment,
        // 	commentList: childCommentList.map(childComment => ({
        // 		...childComment,
        // 		father_id: comment.id
        // 	}))
        // }))

        let vuex_user = this.vuex_user

        let res = await uniCloud.callFunction({
          name: 'star-community-comment',
          data: {
            flag: 1,
            data: {
              my_user_id: vuex_user.id,
              post_id: this.post.id,
              sort: {
                createTime: -1
              },
              skip: (page.num - 1) * page.size,
              limit: page.size
            }
          }
        })
        return res.result.data
      },
      // 切换标签
      selectTab(tab) {
        this.selectedTab = tab
        this.commentList = []
        this.mescroll.resetUpScroll()
      },
      // 自动滑动至某元素，如评论区
      goArea(selector) {
        uni.createSelectorQuery().select(selector).boundingClientRect(res => {
          console.log(res.height);
          uni.pageScrollTo({
            scrollTop: res.height
          })
        }).exec()
      },
      // 选中帖子
      selectPost(post) {
        console.log('selectPost');
        // 重置评论框
        this.$refs.starCommentReplyRef.resetCommentReply()
        this.$refs.starCommentReplyRef.focus = true
      },
      // 长按帖子
      longpressPost(post) {
        console.log('longpressPost');
        this.showPostMoreActionSheet(post)
      },
      // 点击帖子用户头像
      clickPostUserAvatar(post) {
        console.log('clickPostUserAvatar');
        this.goto(`../homepage/homepage?id=${post.user_id}`)
      },
      // 点击贴子用户昵称
      clickPostUserNickname(post) {
        console.log('clickPostUserNickname');
        this.goto(`../homepage/homepage?id=${post.user_id}`)
      },
      // 点击帖子中的关注用户
      clickPostFocusUser(post) {
        console.log('clickPostFocusUser');
        uni.showToast({
          title: '关注成功'
        })
      },
      // 点击帖子中的私聊用户
      clickPostChatUser(post) {
        console.log('clickPostChatUser')
        uni.showToast({
          title: '私聊界面开发中',
          icon: 'none'
        })
      },
      // 点击帖子更多
      clickMore(post) {
        console.log('clickMore');
        this.showPostMoreActionSheet(post)
      },
      // 点击分享帖子
      clickSharePost(post) {
        console.log('clickSharePost');
      },
      async clickDeletePost(post) {
        uni.showModal({
          title: '提示',
          content: '确定要删除该帖子吗？',
          success: async (res) => {
            if (res.confirm) {
              uni.showLoading({
                title: '删除中',
                mask: true
              })
              await uniCloud.callFunction({
                name: 'star-community-comment',
                data: {
                  flag: 2,
                  data: {
                    id: post.id,
                    updateData: {
                      status: 3, // 0 审核中 1 正常 2 审核不通过 3 已删除 4 已违规
                    }
                  }
                }
              })
              uni.navigateBack()
              uni.hideLoading()
              uni.showToast({
                title: '删除成功'
              })
            }
          }
        })
      },
      // 点击评论帖子
      clickCommentPost(post) {
        console.log('clickCommentPost');
        // 重置评论框
        this.$refs.starCommentReplyRef.resetCommentReply()
        this.$refs.starCommentReplyRef.focus = true
        this.goArea('#comment-up-area')
      },
      async toggleLikePost(post, isLiked) {
        console.log('toggleLikePost', isLiked);

        let vuex_user = this.vuex_user

        if (isLiked) {
          try { // 创建user_id和enmu_id的组合唯一索引
            let insert_like_res = await uniCloud.callFunction({
              name: 'star-community-like',
              data: {
                flag: 1,
                data: {
                  id: uuidv4().replace(/-/g, ''),
                  user_id: vuex_user.id,
                  ta_id: post.user_id,
                  type: 0, // 点赞类型：0帖子，1评论
                  enmu_id: post.id, // 点赞类型对应的id
                }
              }
            })
            console.log(insert_like_res);
            uniCloud.callFunction({
              name: 'star-community-count',
              data: {
                flag: 1,
                data: {
                  id: post.id,
                  likeIncCount: 1
                }
              }
            })
          } catch (e) {
            console.log('重复插入');
          }
        } else {
          let delete_like_res = await uniCloud.callFunction({
            name: 'star-community-like',
            data: {
              flag: 2,
              data: {
                user_id: vuex_user.id,
                enmu_id: post.id, // 点赞类型对应的id
              }
            }
          })
          console.log(delete_like_res.result.data);
          if (delete_like_res.result.data.deletedCount > 0) {
            request({
              url: '/count',
              method: 'POST',
              data: {
                flag: 1,
                data: {
                  id: post.id,
                  likeIncCount: -1
                }
              }
            })
          }
        }
      },
      // 点击删除评论
      clickDeleteComment(comment) {
        uni.showModal({
          title: '提示',
          content: '确定要删除该评论吗？',
          success: async (res) => {
            if (res.confirm) {
              uni.showLoading({
                title: '删除中',
                mask: true
              })
              await uniCloud.callFunction({
                name: 'star-community-comment',
                data: {
                  flag: 3,
                  data: {
                    id: comment.id,
                    updateData: {
                      status: 3, // 0 审核中 1 正常 2 审核不通过 3 已删除 4 已违规
                    }
                  }
                }
              })
              this.mescroll.resetUpScroll()
              uni.hideLoading()
              uni.showToast({
                title: '删除成功'
              })
            }
          }
        })
      },
      // 显示帖子更多操作菜单选项
      showPostMoreActionSheet(post) {
        uni.showActionSheet({
          itemList: ['举报'],
          success: async (res) => {
            console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
            uni.showLoading({
              title: '举报中',
              mask: true
            })
            await uniCloud.callFunction({
              name: 'star-community-count',
              data: {
                flag: 1,
                data: {
                  id: post.id,
                  reportIncCount: 1
                }
              }
            })
            uni.hideLoading()
            uni.showToast({
              title: '举报成功'
            })
          },
          fail: (res) => {
            console.log(res.errMsg);
          }
        });
      },

      // 选中评论
      selectComment(comment) {
        console.log('selectComment');

        // 重置评论框
        this.$refs.starCommentReplyRef.resetCommentReply()

        if (comment.father_id) {
          this.$refs.starCommentReplyRef.to_father_id = comment.father_id
          this.$refs.starCommentReplyRef.to_child_id = comment.id
        } else {
          this.$refs.starCommentReplyRef.to_father_id = comment.id
        }
        this.$refs.starCommentReplyRef.to_user_id = comment.user_id
        this.$refs.starCommentReplyRef.placeholder = `回复：${comment.nickname}`
        this.$refs.starCommentReplyRef.focus = true
      },
      // 添加评论至数据库
      async addComment(comment) {
        return await uniCloud.callFunction({
          name: 'star-community-comment',
          data: {
            flag: 2,
            data: {
              ...comment
            }
          }
        })
      },
      // 发送评论
      async sendComment(comment) {
        console.log('发送评论');

        if (!comment.content && comment.imgList.length <= 0) {
          uni.showToast({
            title: '请输入内容',
            icon: 'none'
          })
          return
        }

        uni.showLoading({
          title: '发送中',
          mask: true
        })

        try {
          let vuex_user = this.vuex_user // 从缓存获取我的用户信息
          let status = 1
          let imgList = []
          if (comment.imgList.length > 0) {
            // 创建一个数组来存储上传任务的Promise
            const uploadPromises = []

            // 遍历文件路径数组，为每个文件创建一个上传任务并将其添加到 uploadPromises 数组
            comment.imgList.forEach((filePath) => {
              const cloudPath = `${Date.now()}.jpg`
              const uploadPromise = uniCloud.uploadFile({
                filePath,
                cloudPath,
              });
              uploadPromises.push(uploadPromise)
            })

            // 使用Promise.all()等待所有上传任务完成
            const uploadImgList_res = await Promise.all(uploadPromises)
            // 按选中的图片排序
            uploadImgList_res.sort((a, b) => {
              let indexA = comment.imgList.indexOf(a.filePath);
              let indexB = comment.imgList.indexOf(b.filePath);

              if (indexA < indexB) {
                return -1;
              }
              if (indexA > indexB) {
                return 1;
              }
              return 0;
            })

            for (let img_res of uploadImgList_res) {
              if (img_res.success) {
                imgList.push(img_res.fileID)
              }
            }
          }

          // if (comment.content) {
          // 	let checkContent_res = await request({
          // 		url: '/wechat/msgSecCheck',
          // 		method: 'POST',
          // 		data: {
          // 			scene: 2, // 场景枚举值（1 资料；2 评论；3 论坛；4 社交日志）
          // 			content: comment.content,
          // 			openid: vuex_user.openid_mp,
          // 			nickname: vuex_user.nickname
          // 		}
          // 	})

          // 	console.log(checkContent_res);

          // 	if (checkContent_res.success) {
          // 		let suggest = checkContent_res.data.result.suggest
          // 		if (suggest === 'risky') {
          // 			status = 2
          // 			uni.hideLoading()
          // 			uni.showToast({
          // 				title: '内容违规',
          // 				icon: 'error'
          // 			})
          // 			return
          // 		} else if (suggest === 'pass') {
          // 			status = 1
          // 		}
          // 	}
          // }

          // 必要信息，请替换成实际值
          let myComment = {
            status, // 0 审核中 1 正常 2 审核不通过 3 已删除 4 已违规
            commentCount: 0,
            commentList: [],
            content: comment.content,
            createTime: Date.now(),
            updateTime: Date.now(),
            id: uuidv4().replace(/-/g, ''), // 建议使用uuid去掉“-”（有些api只能传32位） 或 后端添加后返回的id值
            imgList, // 在此之前请将临时路径替换成线上路径
            likeCount: 0,
            post_id: this.post.id,
            user_id: vuex_user.id,
            reportCount: 0
          }

          // 需要回复的父评论
          let fatherComment, fatherCommentIndex = -1
          fatherCommentIndex = this.commentList.findIndex(fatherComment => fatherComment.id === comment
            ?.to_father_id) // 父评论下标
          if (fatherCommentIndex > -1) {
            fatherComment = this.commentList[fatherCommentIndex]
          }

          // 需要回复的子评论
          let childComment, childCommentIndex = -1
          if (fatherCommentIndex > -1) {
            let childCommentList = fatherComment.commentList
            childCommentIndex = childCommentList.findIndex(childComment => childComment.id === comment
              ?.to_child_id)
            if (childCommentIndex > -1) {
              childComment = fatherComment.commentList[childCommentIndex]
            }
          }

          // 回复子评论
          if (fatherComment && childComment) {
            myComment.father_id = fatherComment.id
            myComment.reply_child_id = childComment.id

            // await 添加至数据库
            await this.addComment(myComment)

            myComment.avatar = vuex_user.avatar
            myComment.nickname = vuex_user.nickname
            myComment.isNewComment = true // 优化显示体验，请勿将此字段添加至数据库
            myComment.replyChildComment = childComment
            this.commentList[fatherCommentIndex].commentList.splice(childCommentIndex + 1, 0, myComment)
          }
          // 回复父评论
          else if (fatherComment) {
            myComment.father_id = fatherComment.id

            // await 添加至数据库
            await this.addComment(myComment)

            myComment.avatar = vuex_user.avatar
            myComment.nickname = vuex_user.nickname
            myComment.isNewComment = true // 优化显示体验，请勿将此字段添加至数据库
            this.commentList[fatherCommentIndex].commentList.unshift(myComment)
          }
          // 回复帖子
          else {
            // await 添加至数据库
            await this.addComment(myComment)

            myComment.avatar = vuex_user.avatar
            myComment.nickname = vuex_user.nickname
            this.commentList.unshift(myComment)
          }

          // 重置评论框
          this.$refs.starCommentReplyRef.resetCommentReply()
          this.$refs.starCommentReplyRef.placeholder = comment.placeholder // 延用回复占位符
          this.$refs.starCommentReplyRef.to_father_id = comment.to_father_id // 延用回复父评论
          this.$refs.starCommentReplyRef.to_child_id = comment.to_child_id // 延用回复子评论
          this.$refs.starCommentReplyRef.to_user_id = comment.to_user_id // 延用回复谁
          uni.hideLoading()
          if (status === 1) {
            uni.showToast({
              title: '发送成功'
            })
          } else {
            uni.showToast({
              title: '发送成功，等待审核',
              icon: 'none'
            })
          }
        } catch (err) {
          console.log(err);
          uni.hideLoading()
          uni.showToast({
            title: '发送失败',
            icon: 'error'
          })
        }
      },
      // 长按评论
      longpressComment(comment) {
        console.log('longpressComment');
        this.showCommentMoreActionSheet(comment)
      },
      // 点击评论用户头像
      clickCommentUserAvatar(comment) {
        console.log('clickCommentUserAvatar');
        this.goto(`../homepage/homepage?id=${comment.user_id}`)
      },
      // 点击评论用户昵称
      clickCommentUserNickname(comment) {
        console.log('clickCommentUserNickname');
        this.goto(`../homepage/homepage?id=${comment.user_id}`)
      },
      // 点击评论回复用户昵称
      clickCommentReplyUserNickname(comment) {
        console.log('clickCommentReplyUserNickname');
        if (comment.replyChildComment) console.log(comment.replyChildComment.user_id);
        this.goto(`../homepage/homepage?id=${comment.replyChildComment.user_id}`)
      },
      // 点击喜欢评论
      async toggleLikeComment(comment, isLiked) {
        console.log('toggleLikeComment', isLiked);

        let vuex_user = this.vuex_user

        if (isLiked) {
          try {
            let insert_like_res = await uniCloud.callFunction({
              name: 'star-community-like',
              data: {
                flag: 1,
                data: {
                  id: uuidv4().replace(/-/g, ''),
                  user_id: vuex_user.id,
                  ta_id: comment.user_id,
                  type: 1, // 点赞类型：0帖子，1评论
                  enmu_id: comment.id, // 点赞类型对应的id
                }
              }
            })
            console.log(insert_like_res.result.data);
            uniCloud.callFunction({
              name: 'star-community-count',
              data: {
                flag: 2,
                data: {
                  id: comment.id,
                  likeIncCount: 1
                }
              }
            })
          } catch (e) {
            console.log('重复点赞');
          }
        } else {
          let delete_like_res = await uniCloud.callFunction({
            name: 'star-community-count',
            data: {
              flag: 2,
              data: {
                user_id: vuex_user.id,
                enmu_id: comment.id, // 点赞类型对应的id
              }
            }
          })
          console.log(delete_like_res.data);
          if (delete_like_res.data.deletedCount > 0) {
            uniCloud.callFunction({
              name: 'star-community-count',
              data: {
                flag: 2,
                data: {
                  id: comment.id,
                  likeIncCount: -1
                }
              }
            })
          }
        }
      },
      // 显示帖子更多操作菜单选项
      showCommentMoreActionSheet(comment) {
        uni.showActionSheet({
          itemList: ['举报'],
          success: async (res) => {
            console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
            uni.showLoading({
              title: '举报中',
              mask: true
            })
            await request({
              url: '/count',
              method: 'POST',
              data: {
                flag: 2,
                data: {
                  id: comment.id,
                  reportIncCount: 1
                }
              }
            })
            uni.hideLoading()
            uni.showToast({
              title: '举报成功'
            })
          },
          fail: (res) => {
            console.log(res.errMsg);
          }
        });
      },
      goto(url) {
        uni.navigateTo({
          url
        })
      }
    }
  }
</script>

<style scoped lang="scss">
  .post-detail {
    padding-bottom: 120rpx; // 评论框底部安全距离

    .comment-top {
      padding: 20rpx;
      width: 100%;
      box-sizing: border-box;
      display: inline-flex;
      align-items: center;
      justify-content: space-between;

      .title {
        font-weight: 700;
      }

      .tab {
        display: flex;

        .tab-item {
          padding: 10rpx;

          &.active {
            font-weight: 700;
          }
        }
      }
    }
  }
</style>